package week_six;

public class LongestCommonSubsequence_1143 {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        text1 = " " + text1;
        text2 = " " + text2;
        int[][] f = new int[m + 1][n + 1];
        int[][] dir = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    f[i][j] = f[i - 1][j - 1] + 1;
                    dir[i][j] = 0;
                } else if (f[i - 1][j] > f[i][j - 1]) {
                    f[i][j] = f[i - 1][j];
                    dir[i][j] = 1;
                } else {
                    f[i][j] = f[i][j - 1];
                    dir[i][j] = 2;
                }
//                    f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
            }
        }
        print(text1, dir, m, n);
        System.out.println(sb.toString());
        return f[m][n];
    }

    StringBuilder sb = new StringBuilder();

    private void print(String text1, int[][] dir, int i, int j) {
        if (i == 0 || j == 0) return;
        if (dir[i][j] == 0) {
            print(text1, dir, i - 1, j - 1);
            sb.append(text1.charAt(i));
        } else if (dir[i][j] == 1) {
            print(text1, dir, i - 1, j);
        } else
            print(text1, dir, i, j - 1);
    }

    public static void main(String[] args) {
        new LongestCommonSubsequence_1143().longestCommonSubsequence("abcdefege", "acfegccce");

    }
}
